package org.aphelie.romancer.util.message.impl;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;

import org.aphelie.romancer.util.message.MessageBundle;
import org.eclipse.core.runtime.Plugin;

public class MessagesBundleImpl implements MessageBundle {
	
    private ResourceBundle resourceBundle;
    private String bundleName;
    
    private static final String UIU = "org.aphelie.romancer.util.message";

    public MessagesBundleImpl(String bundleName, Plugin plugin) {
        assert (plugin != null);
        try {
            assert (bundleName != null && bundleName.length() > 0);
            ClassLoader classLoader = plugin.getClass().getClassLoader();
            this.resourceBundle = ResourceBundle.getBundle(bundleName, Locale.getDefault(), classLoader);
            this.bundleName = bundleName;
        } catch (Exception e) {
        	System.err.println(e);
        }
    }

    /**
     * @return Returns the resourceBundle.
     */
    public ResourceBundle getResourceBundle() {
        return resourceBundle;
    }

    /**
     * Returns the name of the message bundle.
     */
    public String getBundleName() {
        if (bundleName != null) {
            return bundleName;
        }
        return ""; //No i18N
    }

    /**
     * Returns the string associated to the specified key or <code>null</code>.
     * @param key the key to search.
     */
    public String getString(String key) {
    	System.err.println(resourceBundle);
        try {
            return resourceBundle.getString(key);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Returns the formatted string associated to the specified key or <code>null</code>.
     * If the key is found the associated String is formatted using the
     * <code>java.text.MessageFormat.format(String pattern, Object[] arguments)</code>
     * method.
     * @param key the key to search
     * @param args an array of objects to be formatted and substituted.
     */
    public String getFormattedString(String key, Object[] args) {
        String format = null;
        try {
            format = MessageFormat.format(resourceBundle.getString(key), args);
        } catch (Exception e) {
        	return null;
        }
        return format;
    }
}
